//
//  SearchTableViewController.m
//  BleSDK
//
//  Created by wakeup on 2018/10/25.
//  Copyright © 2018年 mr mao. All rights reserved.
//

#import "SearchTableViewController.h"
#import "TextViewController.h"
#import "XHToast.h"
#import "BleBaseHeader.h"

@interface SearchTableViewController ()<BleManagerDelegate>

@property (nonatomic, strong) NSMutableArray *bleArray;

@end

@implementation SearchTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    bleSelf.delegate = self;
    [bleSelf ble_startScanBleDevicesWithDuration:NSIntegerMax];
}

#pragma mark - BleManagerDelegate
//蓝牙状态打开回调方法
- (void)bleBack_state_On {
    [bleSelf ble_startScanBleDevicesWithDuration:NSIntegerMax];
}

//搜索到设备回调方法
- (void)bleBack_scanDevicesWithBleArray:(NSMutableArray *)bleArray {
    self.bleArray = bleArray;
    [self.tableView reloadData];
}

//连接设备成功回调方法
- (void)bleBack_connectDeviceSuccessWithPeripheral:(CBPeripheral *)peripheral {
    TextViewController *text = [[TextViewController alloc] init];
    [self.navigationController pushViewController:text animated:YES];
    [XHToast showCenterWithText:@"已连接"];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.bleArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"BleCell"];
    BleModel *model = self.bleArray[indexPath.row];
    cell.textLabel.text = model.name;
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.detailTextLabel.text = model.mac;
    cell.detailTextLabel.font = [UIFont systemFontOfSize:15];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    BleModel *model = self.bleArray[indexPath.row];
    [bleSelf ble_connectBleDevice:model.peripheral];
}

//重新搜索
- (IBAction)clickSearchAgainBtn:(id)sender {
    [bleSelf ble_startScanBleDevicesWithDuration:NSIntegerMax];
}

- (NSMutableArray *)bleArray {
    if (_bleArray == nil) {
        _bleArray = [[NSMutableArray alloc]init];
    }
    return _bleArray;
}


@end
